package com.motong.gongdan.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.motong.gongdan.config.wechat.ConfigurationService;
import com.motong.gongdan.controller.system.ProduceController;
import com.motong.gongdan.entity.*;
import com.motong.gongdan.job.QuartzBean;
import com.motong.gongdan.job.TaskScheduleModel;
import com.motong.gongdan.mapper.CustomEventMapper;
import com.motong.gongdan.util.*;
import com.motong.gongdan.vo.H5Vo.Dashboard.vo.ProcessStatisticsVo;
import com.motong.gongdan.vo.system.otherVo.WorkOrderHandleVo;
import com.motong.gongdan.vo.system.CustomEvent.MissionEventMsg;
import com.motong.gongdan.vo.system.CustomEvent.WorkOrderEventMsg;
import com.motong.gongdan.vo.system.CustomEvent.WorkReportEventMsg;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author:fff
 * @time:2022/5/16
 */
@Service
public class CustomEventService extends ServiceImpl<CustomEventMapper, CustomEvent> {

    @Resource
    CustomEventService customEventService;
    @Resource
    UserService userService;
    @Resource
    ConfigurationService configurationService;
    @Resource
    ProductService productService;
    @Resource
    EventLogService eventLogService;
    @Resource
    DictService dictService;
    @Resource
    MissionService missionService;
    @Resource
    WorkOrderService workOrderService;
    @Resource
    DepartmentsService departmentsService;
    @Resource
    private ProcessesService processesService;

    @Resource
    private ProduceController produceController;

    public void sendCustomEventMsg(Integer type, Integer customType, Integer customDataType, WorkOrder wo, Mission mission, WorkReport workReport) {
        List<CustomEvent> customEventList = customEventService.list(new QueryWrapper<CustomEvent>().eq("state", 0).eq("type", type).eq("custom_type", customType).eq("custom_data_type", customDataType));
        if (!CollectionUtils.isEmpty(customEventList)) {
//            String token = (String) RedisUtil.get("access_token");
            String token = "";
            //数据变更时的初始数据
            WorkOrder workOrder = workOrderService.getOne(new LambdaQueryWrapper<WorkOrder>().eq(WorkOrder::getCode, Objects.nonNull(mission) ? mission.getWorkOrderCode() : "-1"));

            if (StringUtil.isBlank(token)) {
                cn.hutool.json.JSONObject jsonObject = configurationService.getAccessToken();
                token = jsonObject.getStr("access_token");
            }
            String finalToken = token;
            customEventList.forEach(c -> {
                List<String> ids = new ArrayList<>();

                if (c.getEventType() == 0) {
                    if (StringUtil.isNotBlank(c.getUserId())) {
                        ids.addAll(Arrays.asList(c.getUserId().split(",")));
                    }
                    if (StringUtil.isNotBlank(c.getDepId())) {
                        Arrays.asList(c.getDepId().split(",")).forEach(d -> {
                            Departments departments = departmentsService.getById(Integer.valueOf(d));
                            if (departments != null) {
                                ids.addAll(Arrays.asList(departments.getIds().split(",")));
                            }
                        });
                    }
                    if (!CollectionUtils.isEmpty(ids)) {
                        EventLog el = new EventLog();
                        AtomicReference<String> msgR = new AtomicReference<>("");
                        ids.forEach(u -> {
                            User user = userService.getById(Integer.valueOf(u));
                            if (user != null && StringUtil.isNotBlank(user.getOpenid())) {
                                if (type == 0) {
                                    if (StringUtil.isNotBlank(c.getDataCondition())) {
                                        boolean res = handleDataConditionWorkOrder(c.getDataCondition(), type, wo);
                                        if (res) {
                                            if (StringUtil.isNotBlank(c.getPushMess())) {
                                                JSONObject jsonObject = JSON.parseObject(c.getPushMess());
                                                WorkOrderEventMsg msg = jsonObject.toJavaObject(WorkOrderEventMsg.class);
                                                msg = handleWorkOrderEventMsg(msg, wo);
                                                msg.setWorkOrderId(wo.getId());
                                                msgR.set(configurationService.sendMsgWorkOrder(msg, user.getOpenid(), finalToken));
                                            }
                                        }
                                    } else {
                                        JSONObject jsonObject = JSON.parseObject(c.getPushMess());
                                        WorkOrderEventMsg msg = jsonObject.toJavaObject(WorkOrderEventMsg.class);
                                        handleWorkOrderEventMsg(msg, wo);
                                        msg.setWorkOrderId(wo.getId());
                                        msgR.set(configurationService.sendMsgWorkOrder(msg, user.getOpenid(), finalToken));
                                    }
                                } else if (type == 1) {
                                    if (c.getEventType() == 0) {
                                        JSONObject jsonObject = JSON.parseObject(c.getPushMess());
                                        MissionEventMsg msg = jsonObject.toJavaObject(MissionEventMsg.class);
                                        if (StringUtil.isNotBlank(c.getDataCondition())) {
                                            boolean res = handleDataConditionWorkOrder(c.getDataCondition(), type, mission);
                                            if (res) {
                                                msg = handleMissionEventMsg(msg, mission, null);
                                                msg.setMissionId(mission.getId());
                                                msgR.set(configurationService.sendMsgMission(msg, user.getOpenid()));
                                            }
                                        } else {
                                            msg = handleMissionEventMsg(msg, mission, null);
                                            msg.setMissionId(mission.getId());
                                            msgR.set(configurationService.sendMsgMission(msg, user.getOpenid()));
                                        }
                                    } else {
                                        if (StringUtil.isNotBlank(c.getDataCondition())) {
                                            boolean res = handleDataConditionWorkOrder(c.getDataCondition(), type, mission);
                                            if (res) {
                                                handleMissionDataChange(mission, c);
                                            }
                                        } else {
                                            handleMissionDataChange(mission, c);
                                        }
                                        msgR.set("数据变更");
                                    }
                                } else if (type == 2) {
//                                JSONObject jsonObject = JSON.parseObject(c.getPushMess());
                                    WorkReportEventMsg msg = JSONUtil.toBean(c.getPushMess(), WorkReportEventMsg.class);
                                    if (StringUtil.isNotBlank(c.getDataCondition())) {
                                        boolean res = handleDataConditionWorkOrder(c.getDataCondition(), type, workReport);
                                        if (res) {
                                            msg.setWorkReportId(workReport.getId());
                                            msg = handleWorkReportEventMsg(msg, workReport);
                                            msgR.set(configurationService.sendMsgReport(msg, user.getOpenid()));
                                        }
                                    } else {
                                        msg.setWorkReportId(workReport.getId());
                                        msg = handleWorkReportEventMsg(msg, workReport);
                                        msgR.set(configurationService.sendMsgReport(msg, user.getOpenid()));
                                    }
                                }
                            }
                        });
                        if (StringUtil.isNotBlank(msgR.get())) {
                            el.setEventId(c.getId());
                            el.setMsg(msgR.get());
                            el.setState(0);
                            el.setTime(new Date());
                            eventLogService.save(el);
                        }
                    }
                } else {
                    if (StringUtil.isNotBlank(c.getDataCondition())) {
                        boolean res = handleDataConditionWorkOrder(c.getDataCondition(), type, mission);
                        if (!res) {
                            return;
                        }
                    }
                    // 获取工序列表
                    List<ProcessStatisticsVo> processData = processesService.getBaseMapper().getByOrderCodes(Collections.singleton(workOrder.getCode())).stream().sorted((f, s) -> ((f.getLast() == 0 || s.getLast() == 0) && !f.getLast().equals(s.getLast())) ? (f.getLast() == 0 ? 1 : -1) : (f.getLast() - s.getLast())).collect(Collectors.toList());
                    if (c.getExecuteForm() == 0 && c.getFilterCondition() == 0 && Objects.nonNull(c.getExecuteAction())) {
                        produceController.workOrderHandle(new WorkOrderHandleVo().setId(workOrder.getId()).setState(c.getExecuteAction() == 0 ? 1 : 2));
                    }
                    if (c.getExecuteForm() == 1) {
                        int indexOf = CollectionUtil.indexOf(processData, i -> i.getMissionId().equals(mission.getId()));
                        if (indexOf >= 0) {
                            int offset = (c.getFilterCondition() == 0 ? -1 : (c.getFilterCondition() == 1 ? 1 : 0));
                            int targetIndex = (indexOf + offset);
                            if (targetIndex >= 0 && targetIndex <= processData.size() - 1) {
                                ProcessStatisticsVo processStatisticsVo = processData.get(targetIndex);
                                Mission targetMission = new Mission().setId(processStatisticsVo.getMissionId());
                                if (c.getExecuteAction() == 0) {
                                    targetMission.setProcessState(1).setActualStartTime(new Date());
                                } else if (c.getExecuteAction() == 1) {
                                    targetMission.setProcessState(2).setActualEndTime(new Date());
                                }
                                missionService.updateById(targetMission);
                            }
                        }
                    }

                }

            });
        }

    }

    public void handleMissionDataChange(Mission mission, CustomEvent c) {
        if (c.getExecuteForm() == 0) {//工单
            WorkOrder workOrder = workOrderService.getOne(new QueryWrapper<WorkOrder>().eq("code", mission.getWorkOrderCode()));
            if (workOrder != null) {
                if (c.getExecuteAction() == 0) {
                    workOrder.setState(1);
                } else {
                    workOrder.setState(2);
                }
                workOrderService.updateById(workOrder);
            }
        } else {//任务
            Mission handleM = null;
            if (c.getFilterCondition() == 0) {
                WorkOrder workOrder = workOrderService.getOne(new QueryWrapper<WorkOrder>().eq("code", mission.getWorkOrderCode()));
                if (mission.getLast() != 0) {
                    handleM = missionService.getOne(new QueryWrapper<Mission>().eq("work_order_code", mission.getWorkOrderCode()).eq("last", mission.getLast() - 1));
                } else {
                    handleM = missionService.getOne(new QueryWrapper<Mission>().eq("last", workOrder.getProcessId().split(",").length - 1).eq("work_order_code", mission.getWorkOrderCode()));
                }
            } else if (c.getFilterCondition() == 1) {
                if (mission.getLast() != 0) {
                    handleM = missionService.getOne(new QueryWrapper<Mission>().eq("work_order_code", mission.getWorkOrderCode()).eq("last", mission.getLast() + 1));
                } else {
                    handleM = mission;
                }
            } else {
                handleM = mission;
            }
            if (handleM != null) {
                if (c.getExecuteAction() == 0) {
                    handleM.setProcessState(1);
                } else {
                    handleM.setProcessState(2);
                }
                missionService.updateById(handleM);
            }
        }
    }

    public boolean handleDataConditionWorkOrder(String dataCondition, Integer type, Object o) {
        List<Dict> dictList = dictService.list(new QueryWrapper<Dict>().eq("type", type));
        Map<String, Object> map = new HashMap<>();
        AtomicReference<String> condition = new AtomicReference<>("");
        dictList.forEach(d -> {
            if (dataCondition.contains(d.getKeyS())) {
                String reg = StringUtil.regReplace(dataCondition);
                String dictReg = StringUtil.regReplace(d.getKeyS());
                if (StringUtil.isNotBlank(condition.get())) {
                    reg = StringUtil.regReplace(condition.get());
                }
                condition.set(reg.replace(dictReg, d.getValueS()));
                if (condition.get().contains("product")) {
                    try {
                        Field productId = o.getClass().getDeclaredField("productId");
                        productId.setAccessible(true);
                        int productIdInt = Convert.toInt(productId.get(o));
                        Product product = productService.getById(productIdInt);
                        if (product != null) {
                            condition.set(condition.get().replace("productName", product.getName())
                                    .replace("productCode", product.getCode()).replace("productSpecification", product.getSpecification()));
                        }
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                Field[] fields = o.getClass().getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    if (field.getName().equals(d.getValueS())) {
                        try {
                            if ("state".equals(field.getName()) || "processState".equals(field.getName())) {
                                if (field.get(o).equals(0)) {
                                    map.put(field.getName(), "未开始");
                                } else if (field.get(o).equals(1)) {
                                    map.put(field.getName(), "执行中");
                                } else if (field.get(o).equals(2)) {
                                    map.put(field.getName(), "已结束");
                                } /*else if (field.get(o).equals(4)) {
                                    map.put(field.getName(), "已暂停");
                                }*/ else {
                                    map.put(field.getName(), "已取消");
                                }
                            } else {
                                map.put(field.getName(), field.get(o));
                            }
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        ExecuteStringAsCodeUtils tool = new ExecuteStringAsCodeUtils();
        boolean res = (boolean) tool.executeString(condition.get(), map);
        return res;
    }

    public WorkOrderEventMsg handleWorkOrderEventMsg(WorkOrderEventMsg msg, WorkOrder wo) {
        List<String> titleList = OwnUtil.extractMessageByRegular(msg.getTitle());
        List<String> workOrderCodeList = OwnUtil.extractMessageByRegular(msg.getWorkOrderCode());
        List<String> productNameList = OwnUtil.extractMessageByRegular(msg.getProductName());
        List<String> timeList = OwnUtil.extractMessageByRegular(msg.getTime());
        List<String> commentList = OwnUtil.extractMessageByRegular(msg.getComment());
        if (!CollectionUtils.isEmpty(titleList)) {
            titleList.forEach(t -> {
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("key_s", t));
                if (dict != null) {
                    try {
                        Field fields = wo.getClass().getDeclaredField(dict.getValueS());
                        fields.setAccessible(true);
                        String newT = StringUtil.regReplace(t);
                        msg.setTitle(StringUtil.regReplace(msg.getTitle()));
                        //状态名称转意中文
                        msg.setTitle(msg.getTitle().replace(newT, dealFieldValue(t, fields.get(wo).toString())));
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        if (!CollectionUtils.isEmpty(workOrderCodeList)) {
            workOrderCodeList.forEach(t -> {
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("key_s", t));
                if (dict != null) {
                    try {
                        Field fields = wo.getClass().getDeclaredField(dict.getValueS());
                        fields.setAccessible(true);
                        String newT = StringUtil.regReplace(t);
                        msg.setWorkOrderCode(StringUtil.regReplace(msg.getWorkOrderCode()));
                        //状态名称转意中文
                        msg.setWorkOrderCode(msg.getWorkOrderCode().replace(newT, dealFieldValue(t, fields.get(wo).toString())));
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        if (!CollectionUtils.isEmpty(productNameList)) {
            productNameList.forEach(t -> {
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("key_s", t));
                if (dict != null) {
                    String newT = StringUtil.regReplace(t);
                    msg.setProductName(StringUtil.regReplace(msg.getProductName()));
                    if ("productName".equals(dict.getValueS())) {
                        Product p = productService.getById(wo.getProductId());
                        msg.setProductName(msg.getProductName().replace(newT, p.getName()));
                    }
                }
            });
        }
        if (!CollectionUtils.isEmpty(timeList)) {
            timeList.forEach(t -> {
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("key_s", t));
                if (dict != null) {
                    try {
                        Field fields = wo.getClass().getDeclaredField(dict.getValueS());
                        fields.setAccessible(true);
                        String newT = StringUtil.regReplace(t);
                        msg.setTime(StringUtil.regReplace(msg.getTime()));
                        msg.setTime(msg.getTime().replace(newT, TimeUtil.getDateDefaultString((Date) fields.get(wo))));
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                } else {
                    msg.setTime(DateUtil.now());
                }
            });
        }
        if (!CollectionUtils.isEmpty(commentList)) {
            commentList.forEach(t -> {
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("key_s", t));
                if (dict != null) {
                    try {
                        Field fields = wo.getClass().getDeclaredField(dict.getValueS());
                        fields.setAccessible(true);
                        String newT = StringUtil.regReplace(t);
                        msg.setComment(StringUtil.regReplace(msg.getComment()));
                        if (StringUtils.hasLength(msg.getComment()) && Objects.nonNull(fields.get(wo))) {
                            msg.setComment(msg.getComment().replace(newT, dealFieldValue(t, fields.get(wo).toString())));
                        }
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        return msg;
    }

    public MissionEventMsg handleMissionEventMsg(MissionEventMsg msg, Mission mission, WorkReport workReport) {
        List<String> titleList = OwnUtil.extractMessageByRegular(msg.getTitle());
        List<String> workOrderCodeList = OwnUtil.extractMessageByRegular(msg.getWorkOrderCode());
        List<String> processNameList = OwnUtil.extractMessageByRegular(msg.getProcessName());
        List<String> textList = OwnUtil.extractMessageByRegular(msg.getText());
        List<String> userList = OwnUtil.extractMessageByRegular(msg.getUser());
        List<String> msgList = OwnUtil.extractMessageByRegular(msg.getMsg());
        if (!CollectionUtils.isEmpty(titleList)) {
            titleList.forEach(t -> {
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("key_s", t));
                if (dict != null) {
                    try {
                        Field fields = null;
                        String newT = StringUtil.regReplace(t);
                        if (workReport != null && mission != null) {
                            fields = workReport.getClass().getDeclaredField(dict.getValueS());
                            fields.setAccessible(true);
                            msg.setTitle(StringUtil.regReplace(msg.getTitle()));
                            msg.setTitle(msg.getTitle().replace(newT, fields.get(workReport).toString()));
                        } else {
                            fields = mission.getClass().getDeclaredField(dict.getValueS());
                            fields.setAccessible(true);
                            msg.setTitle(StringUtil.regReplace(msg.getTitle()));
                            msg.setTitle(msg.getTitle().replace(newT, fields.get(mission).toString()));
                        }
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        if (!CollectionUtils.isEmpty(workOrderCodeList)) {
            workOrderCodeList.forEach(t -> {
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("key_s", t));
                if (dict != null) {
                    try {
                        Field fields = null;
                        String newT = StringUtil.regReplace(t);
                        if (workReport != null && mission == null) {
                            fields = workReport.getClass().getDeclaredField(dict.getValueS());
                            fields.setAccessible(true);
                            Mission m = missionService.getById(workReport.getMissionId());
                            msg.setWorkOrderCode(StringUtil.regReplace(msg.getWorkOrderCode()));
                            msg.setWorkOrderCode(msg.getWorkOrderCode().replace(newT, m.getWorkOrderCode()));
                        } else {
                            fields = mission.getClass().getDeclaredField(dict.getValueS());
                            fields.setAccessible(true);
                            msg.setWorkOrderCode(StringUtil.regReplace(msg.getWorkOrderCode()));
                            msg.setWorkOrderCode(msg.getWorkOrderCode().replace(newT, fields.get(mission).toString()));
                        }
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        if (!CollectionUtils.isEmpty(processNameList)) {
            processNameList.forEach(t -> {
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("key_s", t));
                if (dict != null) {
                    try {
                        Field fields = null;
                        String newT = StringUtil.regReplace(t);
                        if (workReport != null && mission == null) {
                            fields = workReport.getClass().getDeclaredField(dict.getValueS());
                            fields.setAccessible(true);
                            Mission m = missionService.getById(workReport.getMissionId());
                            msg.setProcessName(StringUtil.regReplace(msg.getProcessName()));
                            msg.setProcessName(msg.getProcessName().replace(newT, m.getProcessName()));
                        } else {
                            fields = mission.getClass().getDeclaredField(dict.getValueS());
                            fields.setAccessible(true);
                            msg.setProcessName(StringUtil.regReplace(msg.getProcessName()));
                            msg.setProcessName(msg.getProcessName().replace(newT, fields.get(mission).toString()));
                        }
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        if (!CollectionUtils.isEmpty(textList)) {
            textList.forEach(t -> {
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("key_s", t));
                if (dict != null) {
                    try {
                        Field fields = null;
                        String newT = StringUtil.regReplace(t);
                        if (workReport != null && mission == null) {
                            fields = workReport.getClass().getDeclaredField(dict.getValueS());
                            fields.setAccessible(true);
                            msg.setText(StringUtil.regReplace(msg.getText()));
                            msg.setText(msg.getText().replace(newT, fields.get(workReport).toString()));
                        } else {
                            fields = mission.getClass().getDeclaredField(dict.getValueS());
                            fields.setAccessible(true);
                            msg.setText(StringUtil.regReplace(msg.getText()));
                            msg.setText(msg.getText().replace(newT, fields.get(mission).toString()));
                        }
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        if (!CollectionUtils.isEmpty(userList)) {
            userList.forEach(t -> {
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("key_s", t));
                if (dict != null) {
                    try {
                        Field fields = null;
                        String newT = StringUtil.regReplace(t);
                        if (workReport != null && mission == null) {
                            fields = workReport.getClass().getDeclaredField(dict.getValueS());
                            fields.setAccessible(true);
                            User u = userService.getById(workReport.getProduceUser());
                            msg.setUser(StringUtil.regReplace(msg.getUser()));
                            msg.setUser(msg.getUser().replace(newT, u.getName()));
                        } else {
                            fields = mission.getClass().getDeclaredField(dict.getValueS());
                            fields.setAccessible(true);
                            msg.setUser(StringUtil.regReplace(msg.getUser()));
                            msg.setUser(msg.getUser().replace(newT, fields.get(mission).toString()));
                        }
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        if (!CollectionUtils.isEmpty(msgList)) {
            msgList.forEach(t -> {
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("key_s", t));
                if (dict != null) {
                    try {
                        Field fields = null;
                        String newT = StringUtil.regReplace(t);
                        if (workReport != null && mission == null) {
                            fields = workReport.getClass().getDeclaredField(dict.getValueS());
                            fields.setAccessible(true);
                            msg.setMsg(StringUtil.regReplace(msg.getMsg()));
                            msg.setMsg(msg.getMsg().replace(newT, fields.get(workReport).toString()));
                        } else {
                            fields = mission.getClass().getDeclaredField(dict.getValueS());
                            fields.setAccessible(true);
                            msg.setMsg(StringUtil.regReplace(msg.getMsg()));
                            msg.setMsg(msg.getMsg().replace(newT, fields.get(mission).toString()));
                        }
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        return msg;
    }


    public WorkReportEventMsg handleWorkReportEventMsg(WorkReportEventMsg msg, WorkReport workReport) {
        List<String> titleList = OwnUtil.extractMessageByRegular(msg.getTitle());
        List<String> processCodeList = OwnUtil.extractMessageByRegular(msg.getProcessCode());
        List<String> productList = OwnUtil.extractMessageByRegular(msg.getProductName());
        List<String> timeList = OwnUtil.extractMessageByRegular(msg.getTime());
        List<String> msgList = OwnUtil.extractMessageByRegular(msg.getMsg());
        if (!CollectionUtils.isEmpty(titleList)) {
            titleList.forEach(t -> {
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("key_s", t));
                if (dict != null) {
                    try {
                        Field fields = null;
                        String newT = StringUtil.regReplace(t);
                        if (workReport != null) {
                            fields = workReport.getClass().getDeclaredField(dict.getValueS());
                            fields.setAccessible(true);
                            msg.setTitle(StringUtil.regReplace(msg.getTitle()));
                            msg.setTitle(msg.getTitle().replace(newT, fields.get(workReport).toString()));
                        }
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        if (!CollectionUtils.isEmpty(processCodeList)) {
            processCodeList.forEach(t -> {
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("key_s", t));
                if (dict != null) {
                    Field fields = null;
                    String newT = StringUtil.regReplace(t);
                    if (workReport != null) {
                        Mission m = missionService.getById(workReport.getMissionId());
                        msg.setProcessCode(StringUtil.regReplace(msg.getProcessCode()));
                        msg.setProcessCode(msg.getProcessCode().replace(newT, m.getProcessCode()));
                    }
                }
            });
        }
        if (!CollectionUtils.isEmpty(productList)) {
            productList.forEach(t -> {
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("key_s", t));
                if (dict != null) {
                    Field fields = null;
                    String newT = StringUtil.regReplace(t);
                    if (workReport != null) {
                        Mission m = missionService.getById(workReport.getMissionId());
                        Product product = productService.getOne(new LambdaQueryWrapper<Product>().eq(Product::getCode, m.getProductCode()));
                        msg.setProductName(StringUtil.regReplace(msg.getProductName()));
                        msg.setProductName(msg.getProductName().replace(newT, product.getName()));
                    }
                }
            });
        }
        if (!CollectionUtils.isEmpty(timeList)) {
            timeList.forEach(t -> {
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("key_s", t));
                if (dict != null) {
                    try {
                        Field fields = null;
                        String newT = StringUtil.regReplace(t);
                        if (workReport != null) {
                            fields = workReport.getClass().getDeclaredField(dict.getValueS());
                            fields.setAccessible(true);
                            msg.setTime(StringUtil.regReplace(msg.getTime()));
                            msg.setTime(msg.getTime().replace(newT, fields.get(workReport).toString()));
                        }
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        if (!CollectionUtils.isEmpty(msgList)) {
            msgList.forEach(t -> {
                Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("key_s", t));
                if (dict != null) {
                    try {
                        Field fields = null;
                        String newT = StringUtil.regReplace(t);
                        if (workReport != null) {
                            fields = workReport.getClass().getDeclaredField(dict.getValueS());
                            fields.setAccessible(true);
                            msg.setMsg(StringUtil.regReplace(msg.getMsg()));
                            msg.setMsg(msg.getMsg().replace(newT, fields.get(workReport).toString()));
                        }
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        return msg;
    }


    public QuartzBean handleEventTime(CustomEvent l) {
        QuartzBean qb = new QuartzBean();
        qb.setEventId(l.getId());
        qb.setJobClass("com.motong.gongdan.job.GroupSchedulerTask");
        if (l.getTime() != null && l.getTimeType() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(l.getTime());
            if (l.getTimeType() == 0) {
                qb.setCron(CronUtil.getCron(l.getTime()));
                qb.setJobName(l.getName());
            } else if (l.getTimeType() == 1) {
                TaskScheduleModel tsm = new TaskScheduleModel();
                tsm.setJobType(1);
                Integer[] dayOfMonths = new Integer[1];
                dayOfMonths[0] = cal.get(Calendar.DAY_OF_MONTH);
                tsm.setDayOfMonths(dayOfMonths);
                tsm.setHour(cal.get(Calendar.HOUR_OF_DAY));
                tsm.setMinute(cal.get(Calendar.MINUTE));
                tsm.setSecond(0);
                qb.setCron(CronUtil.createCronExpression(tsm));
                qb.setJobName(l.getName());
            } else if (l.getTimeType() == 2) {
                TaskScheduleModel tsm = new TaskScheduleModel();
                tsm.setJobType(3);
                Integer[] dayOfWeek = new Integer[1];
                dayOfWeek[0] = cal.get(Calendar.DAY_OF_WEEK);
                tsm.setDayOfWeeks(dayOfWeek);
                tsm.setHour(cal.get(Calendar.HOUR_OF_DAY));
                tsm.setMinute(cal.get(Calendar.MINUTE));
                tsm.setSecond(0);
                qb.setCron(CronUtil.createCronExpression(tsm));
                qb.setJobName(l.getName());
            } else if (l.getTimeType() == 3) {
                TaskScheduleModel tsm = new TaskScheduleModel();
                tsm.setJobType(2);
                Integer[] dayOfMonths = new Integer[1];
                dayOfMonths[0] = cal.get(Calendar.DAY_OF_MONTH);
                tsm.setDayOfMonths(dayOfMonths);
                tsm.setHour(cal.get(Calendar.HOUR_OF_DAY));
                tsm.setMinute(cal.get(Calendar.MINUTE));
                tsm.setSecond(0);
                qb.setCron(CronUtil.createCronExpression(tsm));
                qb.setJobName(l.getName());
            } else if (l.getTimeType() == 4) {
                TaskScheduleModel tsm = new TaskScheduleModel();
                tsm.setJobType(5);
                tsm.setHour(cal.get(Calendar.HOUR_OF_DAY));
                tsm.setMinute(cal.get(Calendar.MINUTE));
                tsm.setSecond(0);
                tsm.setDay(cal.get(Calendar.DAY_OF_MONTH));
                tsm.setMonth(cal.get(Calendar.MONTH) + 1);
                qb.setCron(CronUtil.createCronExpression(tsm));
                qb.setJobName(l.getName());
            }
        }
        return qb;
    }

    private String dealFieldValue(String keyName, String value) {
        if (keyName.contains("工单状态")) {
            String statusChineseName = "";
            switch (value) {
                case "0":
                    statusChineseName = "未开始";
                    break;
                case "1":
                    statusChineseName = "执行中";
                    break;
                case "2":
                    statusChineseName = "已结束";
                    break;
                case "3":
                    statusChineseName = "已取消";
                    break;
//                case "4":
//                    statusChineseName = "已暂停";
//                    break;
            }
            return statusChineseName;
        }
        return value;
    }

}
